package com.kungfuhacking.wristbandpro.chat;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kungfuhacking.wristbandpro.R;
import com.kungfuhacking.wristbandpro.base.view.BaseFragment;
import com.kungfuhacking.wristbandpro.chat.presenter.ChatListAdapter;
import com.kungfuhacking.wristbandpro.chat.presenter.IFragmentChatPresenter;
import com.kungfuhacking.wristbandpro.chat.view.IFragmentChatView;
import com.kungfuhacking.wristbandpro.mqtt.MqttConstant;
import com.kungfuhacking.wristbandpro.mqtt.bean.MessageBean;
import com.kungfuhacking.wristbandpro.widget.swipe.DividerItemDecoration;
import com.kungfuhacking.wristbandpro.widget.swipe.OnItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * 聊天fragment
 * Created by Aaron on 17/3/30.
 */

public class FragmentChat extends BaseFragment implements IFragmentChatView, SwipeRefreshLayout.OnRefreshListener {

    private RecyclerView recycleView;
    private String TAG = getClass().getSimpleName();
    private IFragmentChatPresenter iFragmentChatPresenter = new IFragmentChatPresenter(this);
    private List<MessageBean> chatList = new ArrayList<>();
    private ChatListAdapter chatListAdapter;
    //    private PopupWindow chatPup;
    private SwipeRefreshLayout swipeRefreshLayout;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_two, null);

        initWidget(view);
        //注册EventBus
        EventBus.getDefault().register(this);

        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        iFragmentChatPresenter.getRecentChatList();
    }

    private void initWidget(View view) {

//        TitleBarView tbv = (TitleBarView) view.findViewById(R.id.tbv);
//        tbv.setOnRightClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                moreContact(v);
//            }
//        });
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
//        //为SwipeRefreshLayout设置刷新时的颜色变化，最多可以设置4种
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        recycleView = (RecyclerView) view.findViewById(R.id.recycleView);
        initRecycleView();

    }

//    /**
//     * 消失poup
//     */
//    private void dismissPup() {
//        if (chatPup != null && chatPup.isShowing())
//            chatPup.dismiss();
//    }

//    private void moreContact(View v) {
//
//        View popuView = View.inflate(getActivity(), R.layout.popup_more_contract, null);
//
//        chatPup = new PopupWindow(popuView,
//                DensityUtil.dip2px(getActivity(), 120), ViewGroup.LayoutParams.WRAP_CONTENT);
////        chatPup.setContentView(popuView);
//        chatPup.setOutsideTouchable(true);
//        chatPup.setFocusable(true);
//        chatPup.setBackgroundDrawable(new BitmapDrawable());
//        //x y   DensityUtil.dip2px(getActivity(), 5)
//        chatPup.showAsDropDown(v, 0, 0);
//
//        TextView tv_contract = (TextView) popuView.findViewById(R.id.tv_contract);
//        TextView tv_group = (TextView) popuView.findViewById(R.id.tv_group);
//        TextView tv_add_contract = (TextView) popuView.findViewById(R.id.tv_add_contract);
//
//        tv_contract.setOnClickListener(this);
//        tv_group.setOnClickListener(this);
//        tv_add_contract.setOnClickListener(this);
//
//    }

    private void initRecycleView() {

        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.setItemAnimator(new DefaultItemAnimator());
        chatListAdapter = new ChatListAdapter(getActivity(), chatList);
        recycleView.setAdapter(chatListAdapter);
        recycleView.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST,
                getResources().getDrawable(R.color.bg_gray)));
        recycleView.addOnItemTouchListener(new OnItemClickListener(recycleView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, int position) {

//                Log.d(TAG, "点击时 chatList的个数 :" + chatList.size() + ",点击的position:" + position);

                if (chatList != null && chatList.size() > 0) {
                    chatList.get(position).isRead = 0;
                    chatListAdapter.notifyDataSetChanged();
                    iFragmentChatPresenter.enterChat(chatList.get(position));
                }

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//dragFlags的时候，就会在长按item的时候进入拖动模式，然后就会一直回调onMove函数。我们可以在onMove中进行数据集的更新
                final int dragFlags;//用于拖拽的标志 如果是网格布局，拖动方向为上下左右，否则只有上下方向
                final int swipeFlags;//滑动标记
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    swipeFlags = 0;
                } else {
                    dragFlags = 0;
                    swipeFlags = ItemTouchHelper.START;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                iFragmentChatPresenter.clearChatHistory(viewHolder.getAdapterPosition());
            }

        });
        itemTouchHelper.attachToRecyclerView(recycleView);
    }

    @Override
    public void setAdapterData(List<MessageBean> chatList) {
        this.chatList = chatList;
        chatListAdapter.setChatLists(chatList);
        chatListAdapter.notifyDataSetChanged();
    }

    @Override
    public Context getMyContext() {
        return getActivity();
    }

    //接收到了新消息
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(MessageBean mb) {
        //自己发送的消息则忽略
        if (sp.getString(MqttConstant.USERID, "").equals(mb.sendId)) {
            Log.d(TAG, "自己发送的消息,忽略");
            return;
        }
        iFragmentChatPresenter.receiveMsg(mb);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //反注册EventBus
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        chatList.clear();
        chatListAdapter.setChatLists(chatList);
        chatListAdapter.notifyDataSetChanged();
        iFragmentChatPresenter.getRecentChatList();
        //结束后停止刷新
        swipeRefreshLayout.setRefreshing(false);
    }

//    @Override
//    public void onClick(View v) {
//
//        switch (v.getId()) {
//
//            case R.id.tv_contract://通讯录
//
//                dismissPup();
//                nextActivity(ContractsActivity.class);
//                break;
//
//            case R.id.tv_group://发起群聊
//                dismissPup();
//                Intent mIntent = new Intent(getActivity(), ChooseGroupNumsActivity.class);
//                mIntent.putExtra("style", MqttConstant.CREATE_GROUP);
//                startActivity(mIntent);
//                break;
//
//            case R.id.tv_add_contract://添加好友
//                dismissPup();
//                nextActivity(SearchContractActivity.class);
//                break;
//
//
//        }
//
//    }
}
